package main

import (
	"context"
	"database/sql"
	"encoding/json"
	tools "go-lang-tools"
	"go-lang-tools/goroute"
	"log"
	"os"
	"os/exec"
	"time"

	"github.com/go-vgo/robotgo"

	"github.com/chromedp/chromedp"
)

func main() {
	tools.Logger = tools.WriteLogFile("./log", "")
	closeChrome()
	cookies := []string{
		"kbzw__user_login", "7Obd08_P1ebax9aXXuMmRhshWgMdoJSlsJakptzY1enY5unX1r6blausrZyszt2WqMSs2tjcxKHG2aulmbCgrZqtmt3a1LCCq47p4tnH1petla2Tr7CUs47FotLWoLbo5uDO4sKmrKGogZi43efZ2PDfl7DKgainoaickLjd56udtIzvmKqKl7jj6M3VuNnbwNLtm6yVrY-qrZOgrLi1wcWhieXV4seWqNza3ueKkKTc6-TW3puwmKSRpauprpWekqWplbza0tjU35CsqqqmlKY.", "www.jisilu.cn",
		"kbzw_r_uname", "%E7%81%B0%E5%A4%AA%E7%8B%BC0317", "www.jisilu.cn",
		"kbzw__Session", "qbjoaq3a38g261jq4a38o2bjm6", "www.jisilu.cn",
	}
	dataJson := tools.SendPostRequstJsonWithCookies(`https://www.jisilu.cn/webapi/cb/list_new/`, "", cookies...)
	tools.OutPutInfo(nil, dataJson)
	kzz := make(map[string]interface{})
	json.Unmarshal([]byte(dataJson), &kzz)
	tools.OutPutInfo(nil, "kzz:", kzz)
	tools.OutPutInfo(nil, kzz["data"])
	var mapBondsListAll []map[string]string
	for _, v := range kzz["data"].([]interface{}) {
		mapBondsListAll = append(mapBondsListAll, map[string]string{"code": v.(map[string]interface{})["bond_id"].(string)})
	}
	tools.OutPutInfo(nil, "mapBondsListAll:", mapBondsListAll)

	//return
	allocCtx, _ := chromedp.NewExecAllocator(context.Background(),
		chromedp.ExecPath(`C:\Users\weiwei\AppData\Local\Google\Chrome\Application\chrome.exe`),
		chromedp.Flag("headless", true),
		chromedp.Flag("blink-settings", "imagesEnabled=false"),
		chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`),
	)

	//ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
	//defer cancel()
	//cookies := []string{
	//	"kbzw__user_login", "7Obd08_P1ebax9aXXuMmRhshWgMdoJSlsJakptzY1enY5unX1r6blausrZyszt2WqMSs2tjcxKHG2aulmbCgrZqtmt3a1LCCq47p4tnH1petla2Tr7CUs47FotLWoLbo5uDO4sKmrKGogZi43efZ2PDfl7DKgainoaickLjd56udtIzvmKqKl7jj6M3VuNnbwNLtm6yVrY-qrZOgrLi1wcWhieXV4seWqNza3ueKkKTc6-TW3puwmKSRpauprpWekqWplbza0tjU35CsqqqmlKY.", "www.jisilu.cn",
	//	"kbzw_r_uname", "%E7%81%B0%E5%A4%AA%E7%8B%BC0317", "www.jisilu.cn",
	//	"kbzw__Session", "u3s8i1huk9s0t4em5lfjgiq2l3", "www.jisilu.cn",
	//}
	//tools.ChromedpCheckNavigate(ctx, "https://www.jisilu.cn/data/cbnew/#cb", cookies...)

	//_, err := tools.ChromedpCheckClick(ctx, `#menu_cb`, 3, "https://www.jisilu.cn/webapi/cb/list_new", 5000)
	//if err != nil {
	//	panic(err)
	//}
	//#app > div > div.nav-data > div.data-content.auto-content-width > div.margin-top-20 > div > div.jsl-table.sticky-header > div.jsl-table-body-wrapper > table
	//codesHtml, err := tools.ChromedpCheckOuterHTML(ctx, `#flex_cb > tbody`, 500)
	//if err != nil {
	//	panic(err)
	//}
	//tools.OutPutInfo(nil, codesHtml)
	//doc, err := goquery.NewDocumentFromReader(strings.NewReader(codesHtml))

	//tools.Sleep(100000)
	//=========================================================================

	gorouteCnt := 8
	var jobDones []chan goroute.JobDoneType
	p := goroute.GoRoute{}
	var ctxes []context.Context
	var cancels []context.CancelFunc
	var dsn = `weiwei:123456@tcp(127.0.0.1:3306)/adminfunds?charset=utf8&multiStatements=true`
	var dbs []*sql.DB
	var err error
	for i := 1; i <= gorouteCnt; i++ {
		ctxTmp, cancelTmp := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
		//ctxTmp, cancelTmp = context.WithTimeout(ctxTmp, 25*time.Second)
		ctxes = append(ctxes, ctxTmp)
		cancels = append(cancels, cancelTmp)

		var dbTmp *sql.DB
		dbTmp, err = tools.ConMysql(dsn)
		if err != nil {
			tools.OutPutInfo(err, "链接数据库[程序异常]")
			os.Exit(1)
		}
		dbs = append(dbs, dbTmp)

		//添加job完成通道
		jd := make(chan goroute.JobDoneType)
		jobDones = append(jobDones, jd)

		//defer cancelTmp()

	}
	tools.OutPutInfo(nil, 123)
	p.NewGoRoute(gorouteCnt, 500, ctxes, dbs, jobDones, 30000)
	tools.OutPutInfo(nil, 456)
	t1 := tools.GetTimeUnix(time.Now())
	p.Requirment(mapBondsListAll, pa)
	t2 := tools.GetTimeUnix(time.Now())
	tools.OutPutInfo(nil, "time:", t2-t1)

}

func pa(m map[string]string, ctx context.Context, db *sql.DB, jobDone chan goroute.JobDoneType) {
	//https://www.jisilu.cn/data/convert_bond_detail/127007
	//cookies := []string{
	//	"kbzw__user_login", "7Obd08_P1ebax9aXXuMmRhshWgMdoJSlsJakptzY1enY5unX1r6blausrZyszt2WqMSs2tjcxKHG2aulmbCgrZqtmt3a1LCCq47p4tnH1petla2Tr7CUs47FotLWoLbo5uDO4sKmrKGogZi43efZ2PDfl7DKgainoaickLjd56udtIzvmKqKl7jj6M3VuNnbwNLtm6yVrY-qrZOgrLi1wcWhieXV4seWqNza3ueKkKTc6-TW3puwmKSRpauprpWekqWplbza0tjU35CsqqqmlKY.", "www.jisilu.cn",
	//	"kbzw_r_uname", "%E7%81%B0%E5%A4%AA%E7%8B%BC0317", "www.jisilu.cn",
	//	"kbzw__Session", "qbjoaq3a38g261jq4a38o2bjm6", "www.jisilu.cn",
	//}
	_, err := tools.ChromedpCheckNavigate(ctx, `https://www.jisilu.cn/data/convert_bond_detail/`+m["code"])
	if err != nil {
		jobDone <- goroute.JobDoneType{Err: err, Res: ""}
		return
	}
	zhongjianlv, err := tools.ChromedpCheckText(ctx, `#tc_data > div > div.info_data > table > tbody > tr:nth-child(7) > td:nth-child(2)`, 10)
	if err != nil {
		jobDone <- goroute.JobDoneType{Err: err, Res: ""}
		return
	}

	//tools.InsertAllOneConnect(db, "af_bonds")

	jobDone <- goroute.JobDoneType{Err: nil, Res: "爬取中签率 " + m["code"] + "[正常]" + zhongjianlv}
	return
}
func closeChrome() {
	for i := 1; i <= 3; i++ {
		exec.Command(`taskkill`, `/f`, `/t`, `/im`, "chrome.exe").Start()
		tools.Sleep(1000)
		var ids360chrome []int32
		var err error
		ids360chrome, err = robotgo.FindIds("chrome.exe")
		if err != nil {
			tools.OutPutInfo(err, "查找chrome进程[程序异常]")
			tools.Sleep(500)
			continue
		}

		if len(ids360chrome) > 0 {
			tools.OutPutInfo(nil, "存在chrome进程")
			tools.Sleep(1000)
			continue
		} else {
			tools.OutPutInfo(nil, "结束chrome进程[程序异常]")
			break
		}
	}
}
